<template>
  <div class="table-container">
    <!-- <div class="table-title">容量电费结算情况</div> -->
    <div class="formula-detail">
      <el-collapse v-model="activeNames" class="formula-collapse" accordion @change="handleChange">
        <el-collapse-item title="公式详情" name="1">
          <template #default>
            <div class="formula">风电总价F = 风力发电度数A * 风力单价B</div>
          </template>
        </el-collapse-item>
      </el-collapse>
    </div>

    <el-table
      ref="tableRef"
      :data="tableData"
      :span-method="arraySpanMethod"
      border
      height="calc(100% - 60px)"
      style="width: 100%"
    >
      <!-- <el-table-column type="index" width="70" label="序号"></el-table-column> -->
      <el-table-column prop="index" label="序号" width="70">
        <template #default="scope">
          <span v-if="scope.row.index">{{ scope.row.index }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="project" label="项目" width="155"></el-table-column>
      <el-table-column prop="units" label="计量单位" width="120"></el-table-column>
      <el-table-column prop="public_coal" label="省内公用煤电" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.public_coal"
            :readonly="props.readonly"
            size="small"
            @blur="validateItem(scope.row.public_coal, 'public_coal', patternMap)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="support_coal" label="跨省跨区配套煤电（受入省份承担部分）">
        <template #default="scope">
          <el-input
            v-model="scope.row.support_coal"
            :readonly="props.readonly"
            size="small"
            @blur="validateItem(scope.row.support_coal, 'support_coal', patternMap)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="in_other_coal" label="跨省跨区其他煤电（受入省份承担部分）">
        <template #default="scope">
          <el-input
            v-model="scope.row.in_other_coal"
            :readonly="props.readonly"
            size="small"
            @blur="validateItem(scope.row.in_other_coal, 'in_other_coal', patternMap)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="out_other_coal" label="跨省跨区其他煤电（送出省份承担部分）">
        <template #default="scope">
          <el-input
            v-model="scope.row.out_other_coal"
            :readonly="props.readonly"
            size="small"
            @blur="validateItem(scope.row.out_other_coal, 'out_other_coal', patternMap)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="emergency_coal" label="省内应急煤电">
        <template #default="scope">
          <el-input
            v-model="scope.row.emergency_coal"
            :readonly="props.readonly"
            size="small"
            @blur="validateItem(scope.row.emergency_coal, 'emergency_coal', patternMap)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="others" label="其他"></el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'ChargeSettlement',
  inheritAttrs: false,
});

// import type { CollapseModelValue } from 'element-plus';
import { ChargeSettlementInfo, ChargeSettlementData } from '@/utils/formData';
import { numberDecimal2, validateItem, validate } from '@/utils/pattern';
import FormDataAPI from '@/api/batch/formData.api';

const props = defineProps<{
  readonly?: boolean;
  formId?: string;
  recordId?: string;
  id?: string; // 表单数据对应记录id
  // formData?: any; // 表单数据
  // jsonSchema?: any; // 表单jsonSchema
  batchInfo?: any; // 批次信息
}>();
const activeNames = ref([]);
const handleChange = () => {};

// 列表数据
const tableData = ref<ChargeSettlementInfo[]>(toRaw([]));
const patternMap: any = reactive({
  public_coal: numberDecimal2,
  support_coal: numberDecimal2,
  in_other_coal: numberDecimal2,
  out_other_coal: numberDecimal2,
  emergency_coal: numberDecimal2,
});

// watch(
//   () => props.data,
//   () => {
//     console.log('charge-data-', props.data);
//     tableData.value = props.data;
//   },
//   { deep: true }
// );

// try {
//   if (toRaw(props.data) && '{}' !== JSON.stringify(toRaw(props.data))) {
//     tableData.value = props.data;
//   } else {
//     const tempData = ChargeSettlementData();
//     tableData.value = tempData;
//   }
// } catch (error) {
//   console.log('charge:error-', error);
// }

// 返回一个包含两个元素的数组，第一个元素代表 rowspan，第二个元素代表 colspan
// 也可以返回一个键名为 rowspan 和 colspan 的对象
const arraySpanMethod = ({ rowIndex, columnIndex }: any) => {
  // console.log('span-method: ', row, column, rowIndex, columnIndex);

  if (rowIndex === 0 || rowIndex === 9) {
    if (columnIndex === 0) {
      return [0, 0];
    } else if (columnIndex === 1) {
      return [1, 9];
    }
  }
};

const refreshData = async () => {
  return new Promise((resolve, reject) => {
    FormDataAPI.getFormDataById(props.id)
      .then((data: any) => {
        resolve(data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

onMounted(async () => {
  console.log('charge-');

  if (!props.id) {
    // 表单定义渲染模板
    console.log('first-');
    tableData.value = ChargeSettlementData();
  } else {
    // 第二次进来(有过保存的历史数据)
    const curData: any = await refreshData();
    console.log(`second-${props.id}`, curData);
    if (curData.jsonSchema && '{}' !== curData.jsonSchema) {
      tableData.value = JSON.parse(curData.jsonSchema);
    } else {
      tableData.value = ChargeSettlementData();
    }
  }
});

defineExpose({
  setValue: (value: any) => {
    tableData.value = value;
  },
  getValue: () => {
    return {
      jsonSchema: tableData.value,
      formData: {
        data: tableData.value,
      },
    };
  },
  validate: () => validate(tableData.value, patternMap),
});
</script>

<style lang="scss" scoped>
.formula-detail {
  display: flex;
  justify-content: flex-end;
}
.formula-collapse {
  max-width: 100%;
  border-radius: 10px;
  border: 1px solid #8fb4ff;
  background: #ffffff;
  padding-left: 10px;
  margin-bottom: 10px;

  :deep(.el-collapse-item__header) {
    color: #4080ff;
    background-color: transparent;
  }
}
.formula {
  padding: 5px;
  background-color: transparent;
}
:deep(.el-table_1_column_2) {
  .cell {
    text-align: center;
    font-weight: 600;
  }
}
</style>
